﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Newtonsoft.Json; 
namespace Note_CHUSHI
{
    public partial class NoteBookListForm : Form
    {
            //存储所有笔记簿列表：
            private List<NoteBook> notebooks = new List<NoteBook>();

        //笔记簿目录存储路径
        private string notesRootDirectory;
            
          //UI控件声明
            private ListView noteBookListView;
            private TextBox searchTextBox;
            private ToolStrip toolStrip;
            private ContextMenuStrip listContextMenu;
            
        //加
            private string currentUser;


        //从登录界面之后直接来到这个界面
        public NoteBookListForm(string username)
        {
            currentUser = username;
            notesRootDirectory = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            "EnhancedNoteBooks",
            username); // 添加用户名目录层级
            SetupUI();
            LoadNoteBooks();
            SetupContextMenu();
            this.Text = $"笔记簿列表-当前用户：{username}";
        }

        //设置UI布局
        private void SetupUI()
            {
                this.Text = "笔记簿列表";
                this.Size = new Size(1000, 700);
                this.StartPosition = FormStartPosition.CenterScreen;

                var mainPanel = new Panel { Dock = DockStyle.Fill };

                // 搜索框
                var searchPanel = new Panel { Dock = DockStyle.Top, Height = 50 };
                searchTextBox = new TextBox { Dock = DockStyle.Fill, PlaceholderText = "输入关键词搜索笔记簿…" };
                searchTextBox.TextChanged += SearchTextBox_TextChanged;
                searchPanel.Controls.Add(searchTextBox);

                // 工具栏
                toolStrip = new ToolStrip { Dock = DockStyle.Top };
                toolStrip.Items.Add(new ToolStripButton("新建笔记簿", null, NewNoteButton_Click));
                toolStrip.Items.Add(new ToolStripButton("打开笔记簿", null, OpenNoteButton_Click));
                toolStrip.Items.Add(new ToolStripSeparator());
                toolStrip.Items.Add(new ToolStripButton("退出登录", null, LogoutButton_Click));

                // 笔记簿列表
                noteBookListView = new ListView
                {
                    Dock = DockStyle.Fill,
                    View = View.Details,
                    FullRowSelect = true,
                    MultiSelect = true
                };
                noteBookListView.Columns.Add("笔记簿名称", 400);
                noteBookListView.Columns.Add("创建时间", 150);
                noteBookListView.Columns.Add("笔记数量", 100);
               //noteListView.Columns.Add("修改时间", 150);
            //双击
            noteBookListView.DoubleClick += NoteListView_DoubleClick;

                mainPanel.Controls.Add(noteBookListView);
                mainPanel.Controls.Add(searchPanel);
                this.Controls.Add(mainPanel);
                this.Controls.Add(toolStrip);
            }

            //加载所有笔记簿
            private void LoadNoteBooks()
            {
                noteBookListView.BeginUpdate();
                noteBookListView.Items.Clear();
                notebooks.Clear();

                if (!Directory.Exists(notesRootDirectory))
                {
                    Directory.CreateDirectory(notesRootDirectory);
                    noteBookListView.EndUpdate();
                    return;
                }
                //遍历所有笔记簿目录
                foreach (var dir in Directory.GetDirectories(notesRootDirectory))
                {
                    try
                    {
                        var notebook = NoteBook.LoadFromDirectory(dir);
                        notebooks.Add(notebook);

                        var item = new ListViewItem(notebook.Name);
                        item.SubItems.Add(notebook.CreatedTime.ToString("yyyy-MM-dd HH:mm"));
                        item.SubItems.Add(GetNoteCount(dir).ToString());
                        item.Tag = notebook;
                        noteBookListView.Items.Add(item);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"加载笔记簿失败：{ex.Message}");
                    }
                }
                noteBookListView.EndUpdate();
            }
        private int GetNoteCount(string directory)
        {
            return Directory.GetFiles(directory, "*.rtf").Length;
        }

        //设置右键上下菜单，右键删除功能
        private void SetupContextMenu()
            {
                listContextMenu = new ContextMenuStrip();
                var deleteItem = new ToolStripMenuItem("删除");
                var renameItem = new ToolStripMenuItem("重命名");
                deleteItem.Click += DeleteNotes_Click;
                renameItem.Click+= Rename_Click; 
                listContextMenu.Items.Add(deleteItem);
                 listContextMenu.Items.Add(renameItem);
            noteBookListView.ContextMenuStrip = listContextMenu;
            }


            //搜索框文本变化处理
            //获取关键词-笔记簿名称
            private void SearchTextBox_TextChanged(object sender, EventArgs e)
            {
                string keyword = searchTextBox.Text.ToLower();
                foreach (ListViewItem item in noteBookListView.Items)
                {
                    //获取关联笔记簿
                    var notebook = item.Tag as NoteBook;
                    bool match = notebook.Name.ToLower().Contains(keyword);
                    //相应笔记簿黄色高亮显示
                    item.BackColor = match ? Color.LightYellow : Color.White;
                }
            }


            //新建笔记簿
            private void NewNoteButton_Click(object sender, EventArgs e)
            {
            var newNotebook = new NoteBook(currentUser, $"新建笔记簿_{DateTime.Now:MMddHHmm}");
            newNotebook.CreateDirectory(notesRootDirectory);
            LoadNoteBooks(); // 刷新列表
        }
           
        
        //打开笔记簿
            private void OpenNoteButton_Click(object sender, EventArgs e)
            {
            if (noteBookListView.SelectedItems.Count > 0)
            {
                var selectedNotebook = noteBookListView.SelectedItems[0].Tag as NoteBook;
                OpenNoteListForm(selectedNotebook);
            }
            else
            {
                MessageBox.Show("请先选择一个笔记簿", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 打开笔记列表界面
        private void OpenNoteListForm(NoteBook notebook)
        {
            var noteListForm = new NotesListForm(notebook.DirectoryPath);
            noteListForm.FormClosed += (s, args) =>
            {
                this.Show(); // 新增显示主界面
                LoadNoteBooks(); // 刷新列表 
            };
                this.Hide();
            noteListForm.Show();
        }

        // 添加退出登录方法
        private void LogoutButton_Click(object sender, EventArgs e)
            {
                this.Hide();
                var loginForm = new LoginForm();
                loginForm.FormClosed += (s, args) => this.Close();
                loginForm.Show();

            }

            //打开编辑器
            private void OpenNoteEditor(Note note)
            {
                var editor = new NoteEditorForm(note);
                //    editor.FormClosed += (s, args) => LoadNotes();
                editor.FormClosed += (s, args) =>
                {
                    this.Show();
                    LoadNoteBooks();
                };
                this.Hide();
                editor.Show();
            }
            //列表项双击事件处理
            private void NoteListView_DoubleClick(object sender, EventArgs e)
            {
            OpenNoteButton_Click(sender, e);
        }

            //删除笔记菜单点击事件
            private void DeleteNotes_Click(object sender, EventArgs e)
            {
            if (noteBookListView.SelectedItems.Count > 0)
            {
                var result = MessageBox.Show($"确定要删除选中的 {noteBookListView.SelectedItems.Count} 个笔记簿吗?",
                    "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    foreach (ListViewItem item in noteBookListView.SelectedItems)
                    {
                        var notebook = item.Tag as NoteBook;
                        notebook?.Delete();
                    }
                    LoadNoteBooks();
                }
            }
    
            }

        //右键重命名：

        private void Rename_Click(object sender, EventArgs e)
        {
            if (noteBookListView.SelectedItems.Count == 0) return;

            var selectedItem = noteBookListView.SelectedItems[0];
            var notebook = selectedItem.Tag as NoteBook;

            using (var inputDialog = new Form())
            {
                inputDialog.Text = "重命名笔记簿";
                inputDialog.Size = new Size(400, 150);
                inputDialog.StartPosition = FormStartPosition.CenterParent;

                var textBox = new TextBox
                {
                    Text = notebook.Name,
                    Dock = DockStyle.Top,
                    Margin = new Padding(20)
                };

                var btnConfirm = new Button
                {
                    Text = "确认",
                    DialogResult = DialogResult.OK,
                    Dock = DockStyle.Bottom
                };

                inputDialog.Controls.Add(textBox);
                inputDialog.Controls.Add(btnConfirm);
                inputDialog.AcceptButton = btnConfirm;

                if (inputDialog.ShowDialog() == DialogResult.OK)
                {
                    if (!string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        notebook.Rename(textBox.Text.Trim());
                        selectedItem.Text = notebook.Name; // 立即更新列表显示
                        SaveNotebookMeta(notebook); // 新增元数据保存方法
                    }
                }
            }
        }
        private void SaveNotebookMeta(NoteBook notebook)
        {
            var metaPath = Path.Combine(notebook.DirectoryPath, "notebook.meta");
            var metaData = new
            {
                DisplayName = notebook.Name,
                OriginalName = notebook.SecName,
                CreatedTime = notebook.CreatedTime
            };
            File.WriteAllText(metaPath, JsonConvert.SerializeObject(metaData));
        }



    }
}
